package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.CustomerDao;
import com.seadragon.app.ksr.model.Customer;

@Repository("customerDao")
public class CustomerDaoJpaImpl extends AbstractJpaDao implements CustomerDao {

	@Override
	public Customer findByEmail(String email) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
		Root<Customer> root = cq.from(Customer.class);
		cq.select(root);
		cq.where(cb.equal(root.get("email"), email));
		return entityManager.createQuery(cq).getSingleResult();
	}

	@Override
	public List<Customer> findByFirstName(String firstName) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
		Root<Customer> root = cq.from(Customer.class);
		cq.select(root);
		cq.where(cb.equal(root.get("firstName"), firstName));
		return entityManager.createQuery(cq).getResultList();
	}

	@Override
	public void save(Customer customer) {
		entityManager.persist(customer);
	}

	@Override
	public Customer findById(long id) {
		return entityManager.find(Customer.class, id);
	}

	@Override
	public void update(Customer customer) {
		entityManager.merge(customer);
	}

	@Override
	public List<Customer> findAll(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
		Root<Customer> root = cq.from(Customer.class);
		cq.select(root);
		TypedQuery<Customer> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}
}
